/*
 *  NetTalkClientMap.c
 *  NetTalk
 *
 *  Created by Andrey on 09/10/2008.
 *  Copyright 2008 ИУ7-2003. All rights reserved.
 *
 */

#include <stdlib.h>
#include <string.h>
#include "NetTalkClientMap.h"

BEGIN_STRUCT_DECLARATION(NTClientMapEntry)
	AsciiStringPtr clientAddress;
	NTClientInfoPtr clientInfo;
	TAILQ_ENTRY(_NTClientMapEntry) mapEntries;
END_STRUCT_DECLARATION(NTClientMapEntry)

typedef struct NTClientMap* NTClientMapPtr;
TAILQ_HEAD(NTClientMap, _NTClientMapEntry) _ntClientMap = TAILQ_HEAD_INITIALIZER(_ntClientMap);
NTClientMapPtr _ntClientMapPtr = &_ntClientMap;

void InitClientMap()
{
	TAILQ_INIT(&_ntClientMap);
}

Boolean IsClientInMap(AsciiStringPtr clientAddress)
{
	return (GetNTClientInfoByAddress(clientAddress) != NULL);
}

void AddClientToMap(AsciiStringPtr clientAddress, NTClientInfoPtr clientInfo)
{
	if (IsClientInMap(clientAddress) == NO)
	{
		NTClientMapEntryPtr newClientMapEntry = calloc(1, sizeof(NTClientMapEntry));
		newClientMapEntry->clientAddress = clientAddress;
		newClientMapEntry->clientInfo = clientInfo;
		
		TAILQ_INSERT_TAIL(_ntClientMapPtr, newClientMapEntry, mapEntries);
	}
}

NTClientInfoPtr	GetNTClientInfoByAddress(AsciiStringPtr clientAddress)
{
	NTClientMapEntryPtr mapEntry;
	
	TAILQ_FOREACH(mapEntry, _ntClientMapPtr, mapEntries)
	{
		if (mapEntry != NULL && strcmp(mapEntry->clientAddress, clientAddress) == 0)
			return mapEntry->clientInfo;
	}
	
	return NULL;
}

void RemoveClientFromMap(AsciiStringPtr clientAddress)
{
	NTClientMapEntryPtr mapEntry, tempMapEntry;
	
	TAILQ_FOREACH_SAFE(mapEntry, _ntClientMapPtr, mapEntries, tempMapEntry)
	{
		if (mapEntry != NULL && strcmp(mapEntry->clientAddress, clientAddress) == 0)
		{
			TAILQ_REMOVE(_ntClientMapPtr, mapEntry, mapEntries);
			free(mapEntry);
		}
	}
}

void PurgeClientMap()
{
	NTClientMapEntryPtr mapEntry = (NTClientMapEntryPtr)TAILQ_FIRST(&_ntClientMap);
	NTClientMapEntryPtr nextMapEntry;
	
	while (mapEntry != NULL) 
	{
		nextMapEntry = (NTClientMapEntryPtr)TAILQ_NEXT(mapEntry, mapEntries);
		free(mapEntry);
		mapEntry = nextMapEntry;
	}
}